package com.bbs.toutiao.utils;


import com.bbs.toutiao.entity.MailEntity;
import com.bbs.toutiao.exception.BaseException;
import com.bbs.toutiao.exception.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

/**
 * 描述: 邮箱工具类，发送邮件信息
 * 作者： zhangBin
 * 时间： 2023/9/17 21:04
 * 版本： 1.0
 */

@Slf4j
@Component
public class MailUtil {

    @Value(value = "${spring.mail.username}")
    private String MAIL_SENDER; //邮件发送者

    @Resource
    private JavaMailSender javaMailSender;

    /**
     * @param mailEntity 邮件实体类
     */
    public void sendSimpleMail(MailEntity mailEntity) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(MAIL_SENDER);//发送者
            mailMessage.setTo(mailEntity.getRecipient());//接收者
            mailMessage.setSubject(mailEntity.getSubject());//邮件标题
            mailMessage.setText(mailEntity.getContent());//邮件内容
            log.info("邮箱实体类：接收者"+mailEntity.getRecipient());
            javaMailSender.send(mailMessage);//发送邮箱
        } catch (Exception e) {
            log.error("邮件发送失败:" + e.getMessage());
            throw new BaseException(ExceptionEnum.SERVER_BUSY);
        }
    }

}
